package vip.liux.front.domain.models.chat;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import vip.liux.users.UserEto;

import static vip.liux.users.UserEto.EVENT_NAME;

/**
 * Synchronizes chat users with the user service.
 */
@Component
public class ChatUserSynchronizer {

    private final IChatUserRepository userRepository;
    private final ChatUserLookupService chatUserLookupService;

    public ChatUserSynchronizer(IChatUserRepository userRepository, ChatUserLookupService chatUserLookupService) {
        this.userRepository = userRepository;
        this.chatUserLookupService = chatUserLookupService;
    }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = EVENT_NAME + ".Updated"),
                    exchange = @Exchange(value = "${spring.rabbitmq.template.exchange}"),
                    key = EVENT_NAME + ".Updated"
            )
    })
    public void synchronizeUser(UserEto<Long> eventData) {
        ChatUser user = userRepository.findById(eventData.getId()).orElse(null);

        if (user == null) {
            user = chatUserLookupService.findUserById(eventData.getId());
            if (user == null) {
                return;
            }
        }
        if (user.update(eventData)) {
            userRepository.save(user);
        }
    }
}
